package com.tools.service.impl;

import com.google.common.collect.Lists;
import com.tools.commons.response.ResponseCode;
import com.tools.model.entity.PicsEntity;
import com.tools.repository.PicRepository;
import com.tools.service.PicService;
import com.tools.service.UploadStrategy;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Service
public class PicServiceImpl implements PicService {
    public PicServiceImpl(PicRepository picRepository, @Qualifier("qiNiuUploadStrategy") UploadStrategy strategy) {
        this.picRepository = picRepository;
        this.strategy = strategy;
    }

    UploadStrategy strategy;
    PicRepository picRepository;

    @Override
    public List<PicsEntity> upload(MultipartFile... files) {
        if (files == null || files.length == 0) {
            ResponseCode.BAD_REQUEST.throwException("文件为空");
            return null;
        }
        List<PicsEntity> lists = Lists.newArrayList();

        for (MultipartFile file : files) {
            PicsEntity upload = uploadAndSave(file);
            lists.add(upload);
        }
        return lists;
    }

    @Override
    public String getUrl(String ossKey) {
        return "http://pics.minggen.wang/" + ossKey;
    }

    @Override
    public PicsEntity uploadAndSave(MultipartFile file) {
        try {
            InputStream inputStream = file.getInputStream();
            String ossKey = strategy.upload(inputStream);
            PicsEntity build = PicsEntity.builder()
                    .fileName(file.getOriginalFilename())
                    .fileKey(ossKey)
                    .build();
            picRepository.save(build);
            return build;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
